#include "client.h"

Client::Client(QObject* parent): QObject(parent)
{
    tmr = new QTimer();
    tmr->setInterval(1000);

    connect(tmr, SIGNAL(timeout()), this, SLOT(timeIsOver()));
}

Client::~Client()
{
    client.close();
}

void Client::setLabel(QLabel *label)
{
    pLabel = label;
}

void Client::setStatusBar(QStatusBar *StatusBar)
{
    pStatusBar = StatusBar;
}

void Client::start(QString address, quint16 port)
{
    QHostAddress addr(address);
    client.connectToHost(addr, port);

    connect(&client, SIGNAL(readyRead()), this, SLOT(startRead()));
    connect(&client, SIGNAL(connected()), this, SLOT(connected()));
    connect(&client, SIGNAL(disconnected()), this, SLOT(disConnected()));
}

void Client::connected()
{
    pStatusBar->showMessage("成功连接到服务器");
}

void Client::disConnected()
{
    pStatusBar->showMessage("连接已断开");
    client.close();
}

void Client::startTransfer()
{
    if (client.isWritable()) {
        client.write("gp");
        StartRead = true;
    }
}

void Client::startRead()
{
    if (StartRead) {
        tmr->start();
        bufferAll.clear();
        StartRead = false;
    }

    QByteArray ba;

    ba = client.readAll();
    bufferAll.append(ba);

    qDebug() << "Total: " << bufferAll.size();
}

void Client::timeIsOver()
{
    QBuffer buffer(&bufferAll);

    if (bufferAll.isEmpty())
        return;

    QImage myImage;
    myImage.load(&buffer, "JPEG");
    NewPixMap.convertFromImage(myImage,Qt::ColorOnly);
    pLabel->setPixmap(NewPixMap);
    pLabel->setScaledContents(true);
    pStatusBar->showMessage("图片已加载");
    StartRead = false;
}
